/**
 * Created by xuchaosheng on 16/7/13.
 */
directives.directive('map', ["$rootScope", "tools", 'tmp', "$timeout", "$routeParams", "mapServ", function ($rootScope, tools, tmp, $timeout, $routeParams, mapServ) {
    return {
        restrict: 'E',
        scope: true,
        replace: true,
        link: function (scope, element, attr) {
            var config = scope.config = scope.getMap(attr.moduleid ? Number(attr.moduleid) : Number(attr.tmpid));
            var $container = $('.charts-container');
            var base = $container.width();
            var $ele = $(element);
            var option = null;
            var events = {};
            if (!config.moduleId) {
                scope.tipShown = true;
            } else {
                scope.tipShown = false;
            }
            // 地图相关生成区
            var map;
            $timeout(function () {
                map = new BMap.Map("mapVisual-box");
                map.centerAndZoom('北京');
                map.enableScrollWheelZoom();
            }, 500);

            // 手动绘制圆形
            scope.drawCircle = function () {
                map.disableDragging();
                var center = null;
                var circle = null;
                var x = -1, y = -1;

                var mousedownfn = function (e) {
                    center = e.point;
                    x = e.clientX;
                    y = e.clientY;
                }

                var mousemovefn = function (e) {
                    if (!center) {
                        return;
                    }
                    map.removeOverlay(circle);

                    var distance = Math.sqrt((e.clientX - x) * (e.clientX - x) + (e.clientY - y) * (e.clientY - y));
                    circle = mapServ.addCircle(map, center, distance * 50 - 100);
                }

                var removeMarker = function (e, ee, circle) {
                    map.removeOverlay(circle);
                }

                var addCtxMenu = function () {
                    var ctxMenu = new BMap.ContextMenu();
                    ctxMenu.addItem(new BMap.MenuItem('删除', removeMarker.bind(circle)));
                    circle.addContextMenu(ctxMenu);
                }

                var mouseupfn = function (e) {
                    if (!center) {
                        return;
                    }

                    map.removeEventListener('mousedown', mousedownfn);
                    map.removeEventListener('mousemove', mousemovefn);
                    map.removeEventListener('mouseup', mouseupfn);
                    map.enableDragging();
                    addCtxMenu();
                }

                map.addEventListener('mousedown', mousedownfn);
                map.addEventListener('mousemove', mousemovefn);
                map.addEventListener('mouseup', mouseupfn);
            }

            $('.paintForMap .paint').popup({
                popup: $('.custom.popup'),
                position: 'right center',
                hoverable: true,
                on: 'hover'
            });

            scope.checkInfo = {
                babyShops: false,
                populHotMap: false,
                sportBrands: false,
                shoppingCenter: false,
                sportsEquipment: false,
                consumptionIndex: false,
                residentPopulation: false,
                residentPopulation1: false
            };

            $rootScope.$on('POPUL_HOT_MAP_OFF_EV', function () {
                scope.checkInfo.populHotMap = false;
            });

            var laydatas = {
                shoppingCenter: {
                    shijihualian: [],
                    jialefu: [],
                    walmart: [],
                    darunfa: [],
                    wumei: [],
                    legou: []
                },
                sports: {
                    sportBrands: []
                },
                babyShops: {
                    bangbaoshi: [],
                    qiangsheng: [],
                    haohaizi: [],
                    kangbei: [],
                    beiqin: [],
                    haoqi: [],
                },
                population: {
                    residentPopulation: [],
                    residentPopulationMen: [],
                    residentPopulationWomen: []
                }
            };

            scope.$watch('checkInfo.populHotMap', function (checked) {
                if (checked) {
                    $rootScope.$broadcast('POPUL_HOT_MAP_EV');
                }
            });

            // 运动品牌
            scope.$watch('checkInfo.sportBrands', function (checked) {
                if (checked) {
                    scope.showSportBrands();
                } else {
                    /*for (var i in laydatas.sports.sportBrands) {
                     angular.forEach(laydatas.shoppingCenter[i], function (lay) {
                     map.removeOverlay(lay);
                     });
                     laydatas.shoppingCenter[i].length = 0;
                     }*/
                }
            });

            // 消费指数
            scope.$watch('checkInfo.consumptionIndex', function (checked) {
                if (checked) {
                    mapServ.getConsumptionPoints(map);
                } else {
                    mapServ.getConsumptionPoints();
                }
            });

            // 大型商超
            scope.$watch('checkInfo.shoppingCenter', function (checked) {
                if (checked) {
                    scope.showSuperMarkets(laydatas);
                } else {
                    for (var i in laydatas.shoppingCenter) {
                        angular.forEach(laydatas.shoppingCenter[i], function (lay) {
                            map.removeOverlay(lay);
                        });
                        laydatas.shoppingCenter[i].length = 0;
                    }
                }
            });

            // 母婴
            scope.$watch('checkInfo.babyShops', function (checked) {
                if (checked) {
                    scope.showBabyShops();
                } else {
                    for (var i in laydatas.babyShops) {
                        angular.forEach(laydatas.babyShops[i], function (lay) {
                            map.removeOverlay(lay);
                        });
                        laydatas.babyShops[i].length = 0;
                    }
                }
            });

            // 常驻人口
            for (var i = 0; i < 20; i++) {
                (function (i) {
                    scope.$watch('checkInfo.residentPopulation' + i, function (checked) {
                        if (checked) {
                            mapServ.getPopulationDistri(map);
                        } else {
                            mapServ.getPopulationDistri(false);
                        }
                    });
                })(i);
            }

            // 母婴用品分布
            scope.showBabyShops = function () {
                mapServ.localSearch(map, '帮宝适', "/trend-new-BI/assets/img/bangbaoshi.jpg", 50, 33, laydatas.babyShops.bangbaoshi);
                mapServ.localSearch(map, '强生', "/trend-new-BI/assets/img/qiangsheng.jpg", 50, 37, laydatas.babyShops.qiangsheng);
                mapServ.localSearch(map, '好孩子', "/trend-new-BI/assets/img/haohaizi.jpg", 50, 50, laydatas.babyShops.haohaizi);
                mapServ.localSearch(map, '康贝', "/trend-new-BI/assets/img/kangbei.jpg", 50, 21, laydatas.babyShops.kangbei);
                mapServ.localSearch(map, '贝亲', "/trend-new-BI/assets/img/beiqin.jpg", 50, 37, laydatas.babyShops.beiqin);
                mapServ.localSearch(map, '好奇', "/trend-new-BI/assets/img/haoqi.jpg", 50, 35, laydatas.babyShops.haoqi);
            }

            // 商超分布
            scope.showSuperMarkets = function () {
                mapServ.localSearch(map, '沃尔玛', "/trend-new-BI/assets/img/walmart.png", 50, 50, laydatas.shoppingCenter.walmart);
                mapServ.localSearch(map, '物美', "/trend-new-BI/assets/img/wumei.jpg", 50, 20, laydatas.shoppingCenter.wumei);
                mapServ.localSearch(map, '乐购', "/trend-new-BI/assets/img/legou.png", 50, 17, laydatas.shoppingCenter.legou);
                mapServ.localSearch(map, '家乐福', "/trend-new-BI/assets/img/jialefu.png", 50, 42, laydatas.shoppingCenter.jialefu);
                mapServ.localSearch(map, '世纪华联', "/trend-new-BI/assets/img/shijihualian.jpg", 50, 49, laydatas.shoppingCenter.shijihualian);
                mapServ.localSearch(map, '大润发', "/trend-new-BI/assets/img/darunfa.jpg", 50, 19, laydatas.shoppingCenter.darunfa);
            }

            // 运动品牌
            scope.showSportBrands = function () {
                mapServ.localSearch(map, '361', "/trend-new-BI/assets/img/sportBrands/361.png", 50, 32, laydatas.sports.sportBrands);
                mapServ.localSearch(map, '阿迪达斯', "/trend-new-BI/assets/img/sportBrands/adidasi.png", 50, 47, laydatas.sports.sportBrands);
                mapServ.localSearch(map, '彪马', "/trend-new-BI/assets/img/sportBrands/biaoma.png", 50, 32, laydatas.sports.sportBrands);
                mapServ.localSearch(map, '鸿星尔克', "/trend-new-BI/assets/img/sportBrands/erke.png", 50, 24, laydatas.sports.sportBrands);
                mapServ.localSearch(map, '耐克', "/trend-new-BI/assets/img/sportBrands/naike.png", 50, 18, laydatas.sports.sportBrands);
                mapServ.localSearch(map, '纽拜伦', "/trend-new-BI/assets/img/sportBrands/newbalance.png", 50, 28, laydatas.sports.sportBrands);
                mapServ.localSearch(map, '安踏', "/trend-new-BI/assets/img/sportBrands/anta.png", 50, 30, laydatas.sports.sportBrands);
                mapServ.localSearch(map, 'kappa', "/trend-new-BI/assets/img/sportBrands/kappa.png", 50, 43, laydatas.sports.sportBrands);
                mapServ.localSearch(map, "李宁", "/trend-new-BI/assets/img/sportBrands/lining.png", 50, 43, laydatas.sports.sportBrands);
            }

            config.mapType = config.mapType || attr.type;

            scope.recover_fields = function (flag) {

            }

            scope.fullScreen = function () {
                $rootScope.$broadcast('CHART_FULL_SCREEN_EV', option, config.ctitle, config.mapType);
            }

            var menus = [
                {
                    name: '修改标题',
                    icon: 'write icon',
                    fn: function () {
                        if (!config.moduleId) {
                            return;
                        }

                        $rootScope.$broadcast('EDIT_TITLE_EV', config.ctitle, 'FINISH_TITLE_' + config.moduleId);
                        $rootScope.$broadcast('CONTEXTMENU_OFF_EV');

                        // 监听返回的标题
                        $rootScope.$on('FINISH_TITLE_' + config.moduleId, function (e, content) {
                            config.ctitle = content;
                            option.title = {
                                text: config.ctitle,
                                style: {
                                    fontSize: '16px'
                                }
                            }
                            scope.drawChart(option);
                        });
                    }
                },
                {
                    name: '转换为',
                    icon: 'icon line',
                    submenus: []
                },
                {
                    name: '下载为',
                    icon: 'download icon',
                    submenus: [
                        {
                            name: 'JPEG图片',
                            icon: 'file image outline icon',
                            fn: function () {
                            }
                        },
                        {
                            name: 'png图片',
                            icon: 'file image outline icon',
                            fn: function () {
                            }
                        },
                        {
                            name: 'pdf文件',
                            icon: 'file pdf outline icon',
                            fn: function () {
                            }
                        }
                    ]
                },
                {
                    name: '清空',
                    icon: 'erase icon',
                    fn: function () {

                    }
                },
                {
                    name: '删除',
                    icon: 'trash icon',
                    fn: function () {
                        if (config.moduleId) {
                            $rootScope.$broadcast('CONFIRM_EV', {
                                title: '图删除提醒',
                                content: '图表删除之后不可恢复,确定删除吗?',
                                btns: {
                                    yes: {
                                        text: "确定删除",
                                        fn: function () {
                                            chartServ.deleteIbmModuleChartByModuleId(config);
                                        }
                                    },
                                    no: {
                                        text: '取消',
                                        fn: function () {

                                        }
                                    }
                                }
                            });
                        } else {
                            scope.delChart(config.tmpId);
                            // 清空字段
                            $rootScope.$broadcast('FIELD_RECOVER_FROM_CHART_EV', [], []);
                            $rootScope.$broadcast('CONTEXTMENU_OFF_EV');
                            $rootScope.$broadcast('CONFIRM_OFF_EV');
                        }
                    }
                }
            ];

            element[0].addEventListener('contextmenu', function (e) {
                if (e.button == 2) {
                    $rootScope.$broadcast('CONTEXTMENU_EV', e.pageX, e.pageY, menus);
                    e.preventDefault();
                } else {
                }
                e.stopPropagation();
                return false;
            });

            $ele.find('.accordion').accordion().end().find('.aside').on('click', function (e) {
                e.stopPropagation();
            });

            // 初始化
            $ele.addClass('border').css({
                top: config.top <= 1 ? base * config.top + 'px' : config.top + 'px',
                left: config.left <= 1 ? base * config.left + 'px' : config.left + 'px',
                width: config.width <= 1 ? Math.floor(base * config.width) + 'px' : Math.floor(config.width) + 'px',
                height: config.height <= 1 ? Math.floor(base * config.height) + 'px' : Math.floor(config.height) + 'px'
            }).on('click', function (e) {
                e.stopPropagation();
            });

            $ele.find('#mapVisual-box')[0].style.width = $ele.width() + 'px';
            $ele.find('#mapVisual-box')[0].style.height = $ele.height() + 'px';

            /*            scope.styObj = {
             width: '500px',
             height: '500px'
             };*/

            if (base * config.top + $ele.height() > $container.height() - 100) {
                $container.height($container.height() + 150);
            }

            if (config.moduleId) {
                getChartByModuleId(config.moduleId);
            } else {
                $ele.addClass(config.mapType);
            }

            // 监听度量变化事件
            events.MEA_CHANGE_EV_OFF = $rootScope.$on('MEA_CHANGE_EV', function (e, fieldId, meaType) {
                if (scope.selected) {
                    angular.forEach(config.measure, function (dim) {
                        if (dim.fieldId == fieldId) {
                            dim.meaType = meaType;
                        }
                    });
                    addIbmModuleChart();
                }
            });

            // 监听横坐标增加
            events.DIMENSION_ADD_EV_OFF = $rootScope.$on('DIMENSION_ADD_EV', function (e, dimension) {
                if (scope.selected) {
                    config.dimension.push(dimension);
                    addIbmModuleChart();
                }
            });

            // 监听横坐标减少
            events.DIMENSION_REDUCE_EV_OFF = $rootScope.$on('DIMENSION_REDUCE_EV', function (e, columnId) {
                if (scope.selected) {
                    angular.forEach(config.dimension, function (dim, index) {
                        if (dim.columnId == columnId) {
                            config.dimension.splice(index, 1);
                            addIbmModuleChart();
                        }
                    });
                }
            });

            // 监听横坐标覆盖事件
            events.DIMENSION_RECOVER_EV_OFF = $rootScope.$on('DIMENSION_RECOVER_EV', function (e, dimensions) {
                if (scope.selected) {
                    config.dimension = angular.copy(dimensions);
                    addIbmModuleChart();
                }
            });

            // 监听纵坐标增加
            events.MEASURE_ADD_EV_OFF = $rootScope.$on('MEASURE_ADD_EV', function (e, measure) {
                if (scope.selected) {
                    config.measure.push(measure);
                    addIbmModuleChart();
                }
            });

            // 监听纵坐标减少
            events.MEASURE_REDUCE_EV_OFF = $rootScope.$on('MEASURE_REDUCE_EV', function (e, columnId) {
                if (scope.selected) {
                    angular.forEach(config.measure, function (mea, index) {
                        if (mea.columnId == columnId) {
                            config.measure.splice(index, 1);
                            addIbmModuleChart();
                        }
                    });
                }
            });

            // 监听纵坐标覆盖事件
            events.MEASUREMENT_RECOVER_EV_OFF = $rootScope.$on('MEASUREMENT_RECOVER_EV', function (e, measure) {
                if (scope.selected) {
                    config.measure = angular.copy(measure);
                    addIbmModuleChart();
                }
            });

            // 监听主排序事件
            events.MAIN_SORT_EV_OFF = $rootScope.$on('MAIN_SORT_EV', function (e, sortField, sortType) {
                if (scope.selected) {
                    filters.sortField = sortField;
                    filters.sortType = sortType;
                    getChartByModuleId(config.moduleId);
                }
            });

            // 保存
            events.SAVE_EV_OFF = $rootScope.$on('SAVE_EV', function () {
                var base = $container.width();

                if (config.width <= 1) {
                    config.width = $ele.width() / base;
                }
                if (config.height <= 1) {
                    config.height = $ele.height() / base;
                }
                if (config.top <= 1) {
                    config.top = $ele.position().top / base;
                }
                if (config.left <= 1) {
                    config.left = $ele.position().left / base;
                }

                angular.forEach(config.dimension, function (dim) {
                    for (var i in dim) {
                        if (dim[i] === null) {
                            dim[i] = "";
                        }
                    }
                });
                angular.forEach(config.measure, function (mea) {
                    for (var i in mea) {
                        if (mea[i] === null) {
                            mea[i] = "";
                        }
                    }
                });
            });

            // 筛选组件传来筛选条件
            events.FILTER_EV_OFF = $rootScope.$on('FILTER_EV', function (e, conditionId, value) {
                if (value) {
                    filters['condition-' + conditionId] = value;
                } else {
                    filters['condition-' + conditionId] = null;
                }
                getChartByModuleId(config.moduleId);
            });

            // 监听取消预览事件
            events.PREVIEW_OFF_EV_OFF = $rootScope.$on('PREVIEW_OFF_EV', function () {
                filters = {
                    sortField: '',
                    sortType: ''
                };
                if (config.isDrill) {
                    filters.layerNum = 0;
                    filters.downDrillValue = "";
                }
                downDrillValues.length = 0;
                getChartByModuleId(config.moduleId);
            });

            // 监听到联动事件
            events.LINK_EV_OFF = $rootScope.$on('LINK_EV', function (e, link) {
                if (link.id == config.moduleId) {
                    return;
                }
                if (!link.dimensionValue) {
                    filters = {
                        sortField: '',
                        sortType: ''
                    };
                    if (config.isDrill) {
                        filters.layerNum = 0;
                        filters.downDrillValue = "";
                    }
                    downDrillValues.length = 0;
                    getChartByModuleId(config.moduleId);
                    return;
                }
                angular.extend(filters, link);
                getChartByModuleId(config.moduleId);
            });

            events.DEL_CHART_EV_OFF = $rootScope.$on('DEL_CHART_EV', function (e) {
                chartServ.deleteIbmModuleChartByModuleId(config);
            });

            scope.$on('$destroy', function () {
                for (var i in events) {
                    if (i.indexOf('_OFF') != -1) {
                        events[i]();
                    }
                }
            });

            $ele.on('keydown', function (e) {
                if (scope.selected) {
                    if (e.keyCode == 8) {
                    }
                }
            });
        },
        templateUrl: "/trend-new-BI/app/components/common/chartManager/map/mapView.html"
    }
}]);
services.factory('mapServ', ['tools', "$timeout", function (tools, $timeout) {
    return {
        mapTips: {
            heatmap: '建议您使用一个表示城市(如杭州市或杭州)的维度以及一个度量',
        },
    }
}]);